package com.anche.cywebnew.Utils.DES;

import com.alibaba.druid.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;

public class DESHelper {
	//DES加密后转Base64编码
	public static String base64Encrypt(String str, String key){
		return Base64.byteArrayToBase64(encrypt(str.getBytes(),key));
	}
	//Base64解码后解密
	public static String base64Decrypt(String str, String key){
		try {
			return new String(decrypt(Base64.base64ToByteArray(str),key));
		} catch (Exception e) {
			e.printStackTrace();		
			return "";
		}
	}
	/**
	 * 加密
	 * 
	 * @param datasource
	 *            byte[]
	 * @param password
	 *            String
	 * @return byte[]
	 */
	public static byte[] encrypt(byte[] datasource, String password) {
		try {
			//SecureRandom random = new SecureRandom();
			SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
			//random.setSeed(KEY_STRING.getBytes());
			DESKeySpec desKey = new DESKeySpec(password.getBytes());
			// 创建一个密匙工厂，然后用它把DESKeySpec转换成
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(desKey);
			// Cipher对象实际完成加密操作
			Cipher cipher = Cipher.getInstance("DES");
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
			// 现在，获取数据并加密
			// 正式执行加密操作
			return cipher.doFinal(datasource);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param src
	 *            byte[]
	 * @param password
	 *            String
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] src, String password) throws Exception {
		// DES算法要求有一个可信任的随机数源
		SecureRandom random = new SecureRandom();
		// 创建一个DESKeySpec对象
		DESKeySpec desKey = new DESKeySpec(password.getBytes());
		// 创建一个密匙工厂
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		// 将DESKeySpec对象转换成SecretKey对象
		SecretKey securekey = keyFactory.generateSecret(desKey);
		// Cipher对象实际完成解密操作
		Cipher cipher = Cipher.getInstance("DES");
		// 用密匙初始化Cipher对象
		cipher.init(Cipher.DECRYPT_MODE, securekey, random);
		// 真正开始解密操作
		return cipher.doFinal(src);
	}

	public static void main(String args[]){
		try {
			byte[] name = decrypt("ANCHE572".getBytes(), "5B6C7F83836636B12B152A1062DCF1706E49E0CDD6815EF21B3CB0D8E894D9A1");

		}catch (Exception e){
			e.printStackTrace();
		}
	}

}
